/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.user.comment.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.ScoreLogType;
import com.yami.shop.bean.model.UserExtension;
import com.yami.shop.service.UserExtensionService;
import com.yami.shop.user.comment.model.UserScoreDetail;
import com.yami.shop.user.comment.dao.UserScoreDetailMapper;
import com.yami.shop.user.comment.model.UserScoreLog;
import com.yami.shop.user.comment.service.UserScoreDetailService;
import com.yami.shop.user.comment.service.UserScoreLogService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 *
 * @author lhd
 * @date 2020-05-25 15:31:02
 */
@Service
@AllArgsConstructor
public class UserScoreDetailServiceImpl extends ServiceImpl<UserScoreDetailMapper, UserScoreDetail> implements UserScoreDetailService {

    private final UserScoreDetailMapper scoreDetailMapper;
    private final UserExtensionService userExtensionService;
    private final UserScoreLogService userScoreLogService;


    /**
     * 修改用户过期积分
     * @param dateTime 过期时间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateExpireScoreDetail(DateTime dateTime) {

        // 先修改状态为0的积分明细为过期状态
        scoreDetailMapper.updateExpireScoreDetail(dateTime);

        // 1.查询有积分过期的用户
        List<UserScoreDetail> userScoreDetails = scoreDetailMapper.listExpireScoreDetail(dateTime);
        if(CollectionUtils.isEmpty(userScoreDetails)){
            return;
        }
        // 2.修改用户积分信息
        Map<String, List<UserScoreDetail>> userScoreMap = userScoreDetails.stream().collect(Collectors.groupingBy(UserScoreDetail::getUserId));
        List<UserScoreLog> logList = new ArrayList<>();
        List<UserExtension> userExtensions = new ArrayList<>();
        for (String userId : userScoreMap.keySet()) {
            List<UserScoreDetail> detailList = userScoreMap.get(userId);
            int expireScore = detailList.stream().mapToInt(UserScoreDetail::getUsableScore).sum();
            UserExtension userExtension = new UserExtension();
            userExtension.setUserId(userId);
            userExtension.setScore(expireScore);
            userExtensions.add(userExtension);

            // 添加积分日志
            UserScoreLog userScoreLog = new UserScoreLog();
            userScoreLog.setUserId(userId);
            userScoreLog.setScore(expireScore);
            userScoreLog.setSource(ScoreLogType.EXPIRE.value());
            userScoreLog.setCreateTime(new Date());
            userScoreLog.setIoType(0);
            logList.add(userScoreLog);
        }
        // 批量修改用户积分和添加积分日志
        if(CollectionUtils.isNotEmpty(userExtensions)){
            userExtensionService.updateBatchByUserId(userExtensions);
        }
        if(CollectionUtils.isNotEmpty(logList)){
            userScoreLogService.saveBatch(logList);
        }
        // 3.修改积分明细
        for (UserScoreDetail userScoreDetail : userScoreDetails) {
            userScoreDetail.setStatus(-1);
            userScoreDetail.setExpireTime(new Date());
        }
        updateBatchById(userScoreDetails);
    }

    /**
     * 取消订单时修改用户积分和添加日志
     * @param orderNumber 订单号
     * @param userId 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLogAndDetail(String orderNumber, String userId) {
        UserExtension userExtension = userExtensionService.getOne(
                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, userId));
        if(Objects.isNull(userExtension)){
            return;
        }
        //修改积分明细
        List<UserScoreDetail> scoreDetails = list(new LambdaUpdateWrapper<UserScoreDetail>()
                .eq(UserScoreDetail::getBizId, orderNumber).eq(UserScoreDetail::getStatus, 0));
        if(CollectionUtils.isEmpty(scoreDetails)){
            return;
        }
        //要修改的用户积分，状态为-1表示还没过期的可以返还的用户积分
        Integer score = 0;
        for (UserScoreDetail scoreDetail : scoreDetails) {
            score += scoreDetail.getUsableScore();
            scoreDetail.setStatus(1);
        }
        updateBatchById(scoreDetails);
        userExtension.setScore(userExtension.getScore() + score);
        userExtensionService.updateById(userExtension);
        //添加积分日志
        UserScoreLog scoreLog = new UserScoreLog();
        scoreLog.setUserId(userId);
        scoreLog.setBizId(orderNumber);
        scoreLog.setScore(score);
        scoreLog.setSource(ScoreLogType.SCORE_CASH.value());
        scoreLog.setCreateTime(DateUtil.date());
        scoreLog.setIoType(1);
        userScoreLogService.save(scoreLog);
    }
}
